import React, { Component } from 'react'
import {withRouter} from 'react-router-dom'
import {formateDate} from '../../utils/dateUtils'
import {createFormData} from "../../utils/creatFormData"
import memoryUtils from '../../utils/memoryUtils'
import Demo from './tabs.jsx'
import storageUtils from '../../utils/storageUtils'
 import router from '../../router'
import { Modal, Avatar, Menu, Dropdown, message,Form,Input,Button,Popover} from 'antd';
import './index.scss'
import { ExclamationCircleOutlined,createFromIconfontCN,UserOutlined,FullscreenOutlined,DownOutlined,EditOutlined,LogoutOutlined} from '@ant-design/icons';
// api
import {RestPasswod} from '../../api/account'
const IconFont = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js',
  });
const { confirm } = Modal;
const content = (
    <div className="div1">
      <p style={{color:'white',fontSize:'10px'}}>全屏</p>
    </div>
);
const content1 = (
    <div className="div1">
      <p style={{color:'white'}}>退出全屏</p>
    </div>
);

 class Header extends Component {
    state = {
        currentTime: formateDate(Date.now()),
        visible_edit:false,
        old_password:'',
        isFullScreen: false
    }

    handleFullScreen = () => {
        if (!this.state.isFullScreen) {
          this.requestFullScreen();
        } else {
          this.exitFullscreen();
          setTimeout(()=>{
            this.setState({isFullScreen:false})
        },500) 
        //   this.setState({isFullScreen: false})
        }
        
    };
    
    //退出全屏
    exitFullscreen = () => {
        if (document.exitFullscreen) {  
            document.exitFullscreen();  
        }  
        else if (document.mozCancelFullScreen) {  
            document.mozCancelFullScreen();  
        }  
        else if (document.webkitCancelFullScreen) {  
            document.webkitCancelFullScreen();  
        }  
        else if (document.msExitFullscreen) {  
            document.msExitFullscreen();  
        } 
    };
    //全屏
    requestFullScreen = () => {
        
        const docElm = document.documentElement;
        if (docElm.requestFullscreen) {
            setTimeout(()=>{
                this.setState({isFullScreen:true})
            },500)             
            docElm.requestFullscreen();  
            
        }  
        else if (docElm.mozRequestFullScreen) {  
            docElm.mozRequestFullScreen();  
        }  
        else if (docElm.webkitRequestFullScreen) {  
            docElm.webkitRequestFullScreen();  
        }  
        else if (docElm.msRequestFullscreen) {  
            docElm.msRequestFullscreen();  
        } 
        
    };
    //监听事件
    watchFullScreen = () => {
         
    };

    onClick = ({ key }) => {
        if(key === '3'){
            this.logOut()
        }
        if(key === '1'){
            this.setState({
                visible_edit:true,
            })
        }
    };
    
    menu = (
        <Menu onClick={this.onClick}>
          <Menu.Item key="1"><EditOutlined />{`修改密码`}</Menu.Item>
          <Menu.Item key="2"><UserOutlined />用户中心</Menu.Item>
          <Menu.Divider />
          <Menu.Item key="3"><LogoutOutlined />退出登录</Menu.Item>
        </Menu>
    );

    getTime = () =>{//时间更新显示
       this.Intervalid= setInterval(() =>{
           // console.log('date.()+'+Date.now())
            const currentTime = formateDate(Date.now())
            this.setState({currentTime})
        }, 1000)
    }

    

    /** 编辑 */
    onHanderEdit = (username) => {
        this.setState({
            visible_edit:true,
            id:username,
        })
    }
    // 重置密码
    resetpassword = (value) => {
        // consolevalue)
        const {new_password} = value
        const {old_password} = this.state
        console.log(new_password,old_password)
        RestPasswod(createFormData({new_password,old_password})).then(response => {
            console.log(response.data)
            message.success('修改密码成功')
        }).catch(error => {
            if(error.response.data){
                if (error.response.data.detail.code=="103")
                    message.error("原密码错误，请重新输入")
            }
            else{
                message.error(error.response)
            }
            // console.log(error.response.data)
        })
     }

    getOld_password = (e)=>{
        let value = e.target.value
        this.setState({old_password:value})
    }

    getTitles = () =>{
        //得到当前请求路径
        const path = this.props.location.pathname
        let title
        router.forEach(item =>{
            if(item.key ===path){//如果当前item对象中的key和path一样，item的title就需要显示
                title = item.title
                // console.log('当前打开的item',item)
            }else if(item.children){
                
                const cItem = item.children.find(cItem => cItem.key ===path)
                if(cItem){
                    // console.log('当前打开的子item',cItem)
                    title =cItem.title
                }
            }
        })
        return title
    }
//     /**
//      * 
//      *第一次render()之后执行一次，一般在此执行异步操作：发ajax请求/启动定时器
//      */
    componentDidMount(){
        // console.log('执行动态跟新componentDidMount')
        this.getTime()
        this.watchFullScreen()
    }
        
//     /*
   // 清除定时器
    
   componentWillUnmount(){
       clearInterval(this.Intervalid)
   }
//     /**
//      * 退出登录
//      */
    logOut= ()=>{
        confirm({
            title: '你确定要退出登录吗?',
            icon: <ExclamationCircleOutlined />,
            content: '退出后，将需要重新认证',
            onOk:() =>{
                //删除保存的user数据
                storageUtils.removeUser();
                memoryUtils.user = {}
                console.log('this'+this);
                //跳转到login
                this.props.history.replace('')
                
            },
            onCancel() {
              console.log('Cancel');
            },
          });
    }


    render() {
        const { currentTime} = this.state
        const user = storageUtils.getUser()
        // const title = this.getTitles()
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 12 },
        };
        return (
            <div className='header' >
                <div className='header-top' id='fullScreenContainer'>
                    <span style={{fontSize:'15px'}}>欢迎您,用户{user.username}!</span>&nbsp;&nbsp;&nbsp;    
                    <Popover color='black' mouseLeaveDelay={0} overlayClassName="overlayClassName" overlayStyle={{color: 'rgb(56, 53, 53)', width:'60px',height:'20px'}} content={this.state.isFullScreen ? content1 : content}>            
                        <span onClick={this.handleFullScreen}><FullscreenOutlined style={{ fontSize: '16px', color: '#08c' }}/></span>
                    </Popover>
                    <Dropdown overlay={this.menu} trigger={['click']} overlayClassName="dropdown">
                        <a className="ant-dropdown-link"  onClick={e => e.preventDefault()}>
                        <Avatar style={{ color: '#f56a00', backgroundColor: '#fde3cf' }}>U</Avatar>
                            {user.username}
                        <DownOutlined />
                        </a>
                    </Dropdown>
                </div>

                <div className='header-bottom'>
                    <div className='header-bottom-left' >
                        {/* {title} */}
                        <Demo />
                    </div>
                    <div className='header-bottom-right'>
                    <span>{currentTime}</span>
                    
                    {/* <img src='###' alt="图标"/> */}
                    {/* <HomeOutlined  style={{ fontSize: '16px', color: '#08c' }}/> */}
                    {/* <span>预留位置</span> */}
                    </div>
                </div>

                {/* 重置密码弹窗 */}
                <Modal title={`重置密码`}
                visible={this.state.visible_edit}   //设置默认隐藏
                onCancel={() => {this.setState({visible_edit:false})}}
                footer={false}   //对话框的底部
                >
                <Form
                    onFinish={this.resetpassword}
                >
                    <Form.Item {...formItemLayout} label="原密码"  rules={[
                        { required: true, message: '密码不能为空!' },
                        ]}>
                            <Input.Password type="password" onChange={this.getOld_password} placeholder="请输入原密码"/>
                    </Form.Item>
                    <Form.Item {...formItemLayout} label="新密码" name="new_password" rules={[
                        { required: true, message: '密码不能为空!' },
                        ({getFieldValue}) => ({
                            validator(role,value){
                                let passwords_value = getFieldValue("old_passwords");
                                if(passwords_value && value !== passwords_value){
                                    return Promise.reject("两次密码不一致")
                                }
                                return Promise.resolve();
                            }
                        })
                        ]}>
                            <Input.Password  type="password" placeholder="请输入新密码"/>
                    </Form.Item>
                        
                    <Form.Item {...formItemLayout} label="确认密码" name="old_passwords" rules={[
                        { required: true, message: '密码不能为空!' },
                        ({getFieldValue}) => ({
                            validator(role,value){
                                if(value !== getFieldValue("new_password")){
                                    return Promise.reject("两次密码不一致")
                                }
                                return Promise.resolve();
                            }
                        })
                        ]}>
                        <Input.Password  type="password" placeholder="请确认新密码"/>
                    </Form.Item>
                    <Form.Item  >
                        <Button type="primary" htmlType="submit"> 提交 </Button>
                    </Form.Item>
                </Form>
                </Modal>
            </div>
        )
    }
}

//暴露
export default withRouter(Header)
